import 'package:demo/app/modules/home/home_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_video_view.dart';

class FloatingWindow extends GetView<HomeController> {
  OverlayEntry? _overlayEntry;
  late double _positionX;
  late double _positionY;
  late double _startX;
  late double _startY;
  bool _isDragging = false;
  final double _containerWidth = 100.0;
  final double _containerHeight = 140.0;
  FloatingWindow({super.key});
  @override
  Widget build(BuildContext context) {
    _positionX = Get.width - _containerWidth;
    _positionY = 0.0;
    _overlayEntry = OverlayEntry(
      builder: (BuildContext context) {
        return Positioned(
          left: _positionX,
          top: _positionY,
          child: GestureDetector(
            onPanStart: _onPanStart,
            onPanUpdate: _onPanUpdate,
            child: Material(
              borderRadius: const BorderRadius.all(Radius.circular(10)),
              child: Container(
                width: _containerWidth,
                height: _containerHeight,
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                ),
                child: ClipRRect(
                  borderRadius: const BorderRadius.all(Radius.circular(10)),
                  child: TRTCCloudVideoView(
                    onViewCreated: (viewId) {
                      controller.state.localViewId = viewId;
                      controller.startLocalPreview();
                    },
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
    Overlay.of(Get.overlayContext!).insert(_overlayEntry!);
    return Container();
  }

  void show() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      build(Get.overlayContext!);
    });
  }

  void hide() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  bool get isShowing => _overlayEntry != null;
  void _onPanStart(DragStartDetails details) {
    _isDragging = true;
    _startX = details.globalPosition.dx;
    _startY = details.globalPosition.dy;
  }

  void _onPanUpdate(DragUpdateDetails details) {
    if (_isDragging) {
      final dx = details.globalPosition.dx - _startX;
      final dy = details.globalPosition.dy - _startY;
      final newX = _positionX + dx;
      final newY = _positionY + dy;
      final screenWidth = Get.width;
      final screenHeight = Get.height;
      final maxX = screenWidth - _containerWidth;
      final maxY = screenHeight - _containerHeight;
      _positionX = newX.clamp(0, maxX);
      _positionY = newY.clamp(0, maxY);
      _startX = details.globalPosition.dx;
      _startY = details.globalPosition.dy;
      _overlayEntry?.markNeedsBuild();
    }
  }

  void _onPanEnd(DragEndDetails details) {
    _isDragging = false;
  }
}
